package com.hltx.interceptor;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hltx.constants.CommonConstant;
import com.hltx.resolver.DefiniteException;
import com.hltx.util.CookieUtil;
import com.hltx.util.ResultInfo;


public class WxSecurityInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		String ua = ((HttpServletRequest) request).getHeader("user-agent").toLowerCase();
		if (StringUtils.isEmpty(ua)) {
			throw new DefiniteException("系统繁忙！");
		}
		
		String requestType = request.getHeader("X-Requested-With");
		String forward = request.getServletPath();
		if (UrlConstant.urlMap.containsKey(forward)) {
			forward = UrlConstant.urlMap.get(forward);
		}
		String params = request.getQueryString();
		if (!StringUtils.isEmpty(params)) {
			forward += "?" + URLEncoder.encode(params, "UTF-8");
		}
		
		if (ua.indexOf("micromessenger") > 0) {// 是微信浏览器

			String openId = (String)request.getSession().getAttribute(CommonConstant.OPEN_KEY);
			if(StringUtils.isEmpty(openId)){
				// 查看Cookie是否存在
				openId = CookieUtil.getValue(request, CommonConstant.OPEN_KEY);
			}
			System.out.println(openId);
			if (StringUtils.isEmpty(openId)) {
				String contextPath = request.getContextPath();
				String url = "/wxValidate/getWxJsApiCode?goUrl="+(StringUtils.isEmpty(forward)?"/index":forward);
				if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
					response.sendRedirect(contextPath + url);
				} else {
					Map<String, Object> resMap = new HashMap<String, Object>();
					resMap.put("result", this.initResult(ResultInfo.ERROR, "wx_not_validate", "微信未认证", url));
					ObjectMapper om = new ObjectMapper();
					response.getWriter().print(om.writeValueAsString(resMap));
				}
				return false;
			} else {
				request.getSession().setAttribute(CommonConstant.OPEN_KEY, openId);
				CookieUtil.setCookie(response, CommonConstant.OPEN_KEY, openId, 15);
			}

		}

		return true;
	}
	
	public ResultInfo initResult(String state, String code, String message,String url){
		ResultInfo ri = new ResultInfo();
		ri.setState(state);
		ri.setCode(code);
		ri.setMessage(message);
		ri.setUrl(url);
		return ri;
	}
}
